
require 'uri'
require 'net/https'
require 'json'

module TheFox
	module VieTra
		
		BASE_URL = 'https://www.wienerlinien.at/ogd_realtime'
		
		class Command
			
			def initialize(api_key, options)
				@api_key = api_key
				@options = options
				
				# puts "BASE_URL #{BASE_URL}"
				# puts "name " + url_path
				# puts "key #{@api_key}"
				# puts "options #{@options}"
			end
			
			def url_path
				nil
			end
			
			def query_builder
				[]
			end
			
			def request
				queries = []
				queries << ['sender', @api_key]
				queries += query_builder
				#pp queries
				
				query = queries
					.map{ |f| f.is_a?(Array) ? f : [f] }
					.select{ |f| f.count > 0 }
					.map{ |f| f.join('=') }.join('&')
				#pp query
				
				uri_s = [[BASE_URL, url_path].join('/'), query].join('?')
				uri = URI(uri_s)
				#puts "uri: '#{uri}'" if $DEBUG || ENV['DEBUG']
				#return
				
				http = Net::HTTP.new(uri.host, uri.port)
				http.use_ssl = true
				#http.verify_mode = OpenSSL::SSL::VERIFY_NONE
				
				http.start do |http|
					request = Net::HTTP::Get.new(uri)
					response = http.request(request)
					code = response.code.to_i
					if code == 200
						json = JSON.parse(response.body)
						
						if json['message']['messageCode'] == 1
							json['data']
						else
							raise "API request failed: code=#{json['message']['messageCode']} value='#{json['message']['value']}'"
						end
					else
						raise "Unknown response code: #{response.code}"
					end
				end
			end
			
		end
		
	end
end
